import React, { useState, useEffect } from 'react';
import { Play, Pause, Square, Clock } from 'lucide-react';
import { fishCategories } from '../data/categories';
import { FishEvent } from '../types';

interface TimerProps {
  onEventSaved: (event: FishEvent) => void;
}

const Timer: React.FC<TimerProps> = ({ onEventSaved }) => {
  const [isRunning, setIsRunning] = useState(false);
  const [seconds, setSeconds] = useState(0);
  const [selectedCategory, setSelectedCategory] = useState(fishCategories[0]);
  const [location, setLocation] = useState('');
  const [description, setDescription] = useState('');

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (isRunning) {
      interval = setInterval(() => {
        setSeconds(seconds => seconds + 1);
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [isRunning]);

  const formatTime = (totalSeconds: number) => {
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const secs = totalSeconds % 60;
    
    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const handleStart = () => {
    setIsRunning(true);
  };

  const handlePause = () => {
    setIsRunning(false);
  };

  const handleStop = () => {
    if (seconds > 0) {
      const event: FishEvent = {
        id: Date.now().toString(),
        type: selectedCategory.id,
        duration: Math.ceil(seconds / 60),
        location: location || '工位',
        description: description || '使用计时器记录的摸鱼时间',
        timestamp: Date.now(),
        date: new Date().toLocaleDateString('zh-CN')
      };
      
      onEventSaved(event);
      
      // 重置计时器
      setSeconds(0);
      setIsRunning(false);
      setLocation('');
      setDescription('');
    }
  };

  const handleReset = () => {
    setSeconds(0);
    setIsRunning(false);
  };

  return (
    <div className="bg-white rounded-lg shadow-md p-6 animate-slide-up hover:shadow-lg transition-shadow duration-300">
      <h2 className="text-xl font-bold text-gray-800 mb-6 flex items-center gap-2">
        <Clock className={`h-5 w-5 ${isRunning ? 'animate-spin' : 'animate-pulse'}`} />
        摸鱼计时器
      </h2>

      {/* 时间显示 */}
      <div className="text-center mb-8 animate-fade-in">
        <div className={`text-6xl font-mono font-bold text-gray-800 mb-2 transition-all duration-300 ${isRunning ? 'animate-pulse text-blue-600' : 'hover:scale-105'}`}>
          {formatTime(seconds)}
        </div>
        <p className="text-gray-600 animate-fade-in-up animation-delay-200">
          {seconds > 0 ? `已摸鱼 ${Math.ceil(seconds / 60)} 分钟` : '开始你的摸鱼时光'}
        </p>
      </div>

      {/* 控制按钮 */}
      <div className="flex justify-center gap-4 mb-6 animate-fade-in-up animation-delay-300">
        {!isRunning ? (
          <button
            onClick={handleStart}
            className="flex items-center gap-2 bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-lg transition-all duration-300 transform hover:scale-105 active:scale-95 hover:shadow-lg animate-bounce-gentle"
          >
            <Play className="h-5 w-5 animate-pulse" />
            开始摸鱼
          </button>
        ) : (
          <button
            onClick={handlePause}
            className="flex items-center gap-2 bg-yellow-500 hover:bg-yellow-600 text-white px-6 py-3 rounded-lg transition-all duration-300 transform hover:scale-105 active:scale-95 hover:shadow-lg animate-pulse"
          >
            <Pause className="h-5 w-5 animate-bounce" />
            暂停
          </button>
        )}
        
        <button
          onClick={handleStop}
          disabled={seconds === 0}
          className="flex items-center gap-2 bg-red-500 hover:bg-red-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white px-6 py-3 rounded-lg transition-all duration-300 transform hover:scale-105 active:scale-95 hover:shadow-lg disabled:transform-none"
        >
          <Square className="h-5 w-5 hover:animate-wiggle" />
          结束并保存
        </button>
      </div>

      {/* 设置区域 */}
      <div className="space-y-4 animate-fade-in-up animation-delay-500">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            摸鱼类型
          </label>
          <div className="grid grid-cols-4 gap-2">
            {fishCategories.map((category, index) => (
              <button
                key={category.id}
                onClick={() => setSelectedCategory(category)}
                className={`p-3 rounded-lg text-center transition-all duration-200 transform hover:scale-110 active:scale-95 animate-fade-in-up ${
                  selectedCategory.id === category.id
                    ? 'bg-blue-500 text-white shadow-md animate-pulse-gentle'
                    : 'bg-gray-100 hover:bg-gray-200 text-gray-700 hover:shadow-md'
                }`}
                style={{ animationDelay: `${index * 50}ms` }}
              >
                <div className="text-2xl mb-1 animate-bounce-gentle">{category.icon}</div>
                <div className="text-xs font-medium">{category.name}</div>
              </button>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              地点
            </label>
            <input
              type="text"
              value={location}
              onChange={(e) => setLocation(e.target.value)}
              placeholder="工位"
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 hover:border-blue-300 focus:scale-105"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              备注
            </label>
            <input
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="记录这次摸鱼的心情"
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 hover:border-blue-300 focus:scale-105"
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Timer;